package com.example.restatr.Atcivity.PetHospital;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.restatr.Atcivity.GovServiceHotline.CreateAppealAt;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.android.material.button.MaterialButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CreateConsultingAt extends AppCompatActivity {
    private Toolbar toolbar;
    private TextView barTitle;
    private EditText search;
    private EditText yjContent;
    private CardView addCard;
    private ImageView img;
    private CardView clear;
    private MaterialButton button;
    private View zzc;
    private LinearLayout loading;
    private File file;
    private Uri uriForFile;
    private String fileName;
    private PopupWindow popupWindow;
    private boolean isImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_create_consulting_at );
        bindView();
        Tools.SetBarTitle( toolbar, barTitle, "创建问题咨询", search, this, false );
        addCard.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View inflate = getLayoutInflater().inflate( R.layout.popupwindow_layout, null );
                popupWindow = new PopupWindow( inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true );
                popupWindow.setOutsideTouchable( true );
                popupWindow.setAnimationStyle( R.style.anim_photo_select );
                popupWindow.showAtLocation( button, Gravity.BOTTOM, 0, 0 );
                popupWindow.setOnDismissListener( new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        zzc.setVisibility( View.GONE );
                    }
                } );
                zzc.setVisibility( View.VISIBLE );
            }
        } );
        clear.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                img.setImageDrawable( getDrawable( R.drawable.ic_round_add_24 ) );
                clear.setVisibility( View.GONE );
                isImg = false;
            }
        } );
        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (button.getText().toString().equals( "提交咨询" )) {
                    if (Tools.isEmptyText( yjContent )) {
                        if (isImg) {
                            UploadImage( file );
                        } else {
                            new Thread( () -> PostQuestionConsultation() ).start();
                        }
                    } else {
                        Toast.makeText( CreateConsultingAt.this, "不能为空", Toast.LENGTH_SHORT ).show();
                    }
                } else {
                    startActivity( new Intent( CreateConsultingAt.this, MyConsultationAt.class ) );
                }
            }
        } );
    }

    private void bindView() {
        toolbar = findViewById( R.id.toolbar );
        barTitle = findViewById( R.id.bar_Title );
        search = findViewById( R.id.search );
        yjContent = findViewById( R.id.yj_content );
        addCard = findViewById( R.id.add_card );
        img = findViewById( R.id.img );
        clear = findViewById( R.id.clear );
        button = findViewById( R.id.button );
        zzc = findViewById( R.id.zzc );
        loading = findViewById( R.id.loading );
    }

    //popupWindow按钮点击事件
    public void ppWindowClick(View view) {
        switch (view.getId()) {
            case R.id.pz:
                file = new File( getExternalCacheDir(), System.currentTimeMillis() + ".jpg" );
                if (!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                uriForFile = FileProvider.getUriForFile( CreateConsultingAt.this, "com.example.restatr.fileprovider", file );
                Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
                intent.putExtra( MediaStore.EXTRA_OUTPUT, uriForFile );
                startActivityForResult( intent, CreateAppealAt.DEFAULT_KEYS_DIALER );
                popupWindow.dismiss();
                break;
            case R.id.xc:
                choosePhoto();
                popupWindow.dismiss();
                break;
            case R.id.qx:
                popupWindow.dismiss();
                break;
        }
    }

    //检测相册权限
    public void choosePhoto() {
        if (ContextCompat.checkSelfPermission( this, Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED) {
            // 真正的去打开相册
            openAlbum();
        } else {
            // 去申请权限
            ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0 );
        }
    }

    //打开相册
    private void openAlbum() {
        Intent intent = new Intent( "android.intent.action.GET_CONTENT" );
        intent.setType( "image/*" );
        startActivityForResult( intent, DEFAULT_KEYS_DISABLE );
    }

    //获取头像路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query( uri, null, selection, null, null );
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString( cursor.getColumnIndex( MediaStore.Images.Media.DATA ) );
            }
            cursor.close();
        }
        return path;
    }

    private void resolveMSFContent(Uri uri) {

        File file = new File( getCacheDir(), "temp_file" + getContentResolver().getType( uri ).split( "/" )[1] );

        try {
            InputStream inputStream = getContentResolver().openInputStream( uri );

            OutputStream outputStream = new FileOutputStream( file );

            byte[] buffer = new byte[4 * 1024];
            int read;
            while ((read = inputStream.read( buffer )) != -1) {
                outputStream.write( buffer, 0, read );
            }
            outputStream.flush();
            displayImage( file.getAbsolutePath() );

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //选择头像Api 19以上
    @TargetApi(19)
    private void handleImageOnApi19(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri( this, uri )) {
            String documentId = DocumentsContract.getDocumentId( uri );
            if (TextUtils.equals( uri.getAuthority(), "com.android.providers.media.documents" )) {
                String id = documentId.split( ":" )[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection );
            } else if (TextUtils.equals( uri.getAuthority(), "com.android.providers.downloads.documents" )) {
                if (documentId != null && documentId.startsWith( "msf:" )) {
                    resolveMSFContent( uri );
                    return;
                }
                Uri contentUri = ContentUris.withAppendedId( Uri.parse( "content://downloads/public_downloads" ), Long.valueOf( documentId ) );
                imagePath = getImagePath( contentUri, null );
            } else {
                String id = documentId.split( ":" )[1];
                imagePath = "/storage/emulated/0/" + id;
            }
        } else if ("content".equalsIgnoreCase( uri.getScheme() )) {
            imagePath = getImagePath( uri, null );
        } else if ("file".equalsIgnoreCase( uri.getScheme() )) {
            imagePath = uri.getPath();
        }
        displayImage( imagePath );
    }

    /**
     * 上传图片到服务器
     */
    private void UploadImage(final File mfile) {
        zzc.setVisibility( View.VISIBLE );
        loading.setVisibility( View.VISIBLE );
        new Thread( new Runnable() {
            @Override
            public void run() {
                final String s = Tools.UploadFiles( "/prod-api/common/upload", MainActivity.sp.getString( "token", "" ), mfile );
                try {
                    JSONObject JieXi = new JSONObject( s );
                    if (JieXi.getInt( "code" ) == 200) {
                        fileName = JieXi.getString( "fileName" );
                        PostQuestionConsultation();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } ).start();
    }

    private void PostQuestionConsultation() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put( "doctorId", getIntent().getIntExtra( "id", 0 ) );
            jsonObject.put( "question", yjContent.getText().toString() );
            if (isImg){
                jsonObject.put( "imageUrls", "/prod-api"+fileName );
            }
            String token = Tools.Post( "/prod-api/api/pet-hospital/inquiry", MainActivity.sp.getString( "token", "" ), jsonObject.toString() );
            JSONObject jx = new JSONObject( token );
            String msg = jx.getString( "msg" );
            int code = jx.getInt( "code" );
            runOnUiThread( () -> {
                Toast.makeText( this, msg, Toast.LENGTH_SHORT ).show();
                if (code == 200) {
                    zzc.setVisibility( View.GONE );
                    loading.setVisibility( View.GONE );
                    button.setText( "查看我的问诊记录" );
                }
            } );
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //显示头像
    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile( imagePath );
            img.setImageBitmap( bitmap );
            isImg = true;
            clear.setVisibility( View.VISIBLE );
            file = new File( imagePath );
        }
    }

    //Activity回调函数
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        if (requestCode == DEFAULT_KEYS_DIALER) {
            if (resultCode == RESULT_OK) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream( uriForFile );
                    Bitmap bitmap = BitmapFactory.decodeStream( inputStream );
                    img.setImageBitmap( bitmap );
                    isImg = true;
                    clear.setVisibility( View.VISIBLE );
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            Toast.makeText( CreateConsultingAt.this, "照片保存在：" + file.getPath(), Toast.LENGTH_SHORT ).show();

        } else if (requestCode == DEFAULT_KEYS_DISABLE) {
            if (resultCode == RESULT_OK) {
                handleImageOnApi19( data );
            }
        }
    }

    //权限申请回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult( requestCode, permissions, grantResults );
        //当接受申请时，打开相册
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openAlbum();
        }
    }
}